package com.fpno.connection;

import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectDemo1 {

    //连接方法一
    @Test
    public void testConnect1() throws SQLException {
        //driver实例化，调用mysql的驱动
        Driver driver=new com.mysql.jdbc.Driver();
        //jdbc:mysql: 协议
        //localhost 地址
        //3306/test 端口及数据库
        String url = "jdbc:mysql://localhost:3306/test";
        //封装用户名和密码
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","");
        Connection con = driver.connect(url, info);
        System.out.println(con);
    }

    //方式二:对方式一的迭代
    @Test
    public void testConnect2() throws Exception {
        //用反射实现获取类的对象
        Class cla = Class.forName("com.mysql.jdbc.Driver");
        Driver driver =(Driver) cla.newInstance();
        //提供要连接的数据库
        String url = "jdbc:mysql://localhost:3306/test";
        //用户名和密码
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","");
        //获取连接
        Connection con = driver.connect(url, info);
        System.out.println(con);
    }

    //方式三 使用DriverManager替换Driver
    @Test
    public void testConnect3() throws Exception{
        //获取类的对象
        Class cls=Class.forName("com.mysql.jdbc.Driver");
        Driver driver=(Driver) cls.newInstance();

        String url="jdbc:mysql://localhost:3306/test";
        String user="root";
        String password="";

        //注册驱动
        DriverManager.registerDriver(driver);

        Connection con = DriverManager.getConnection(url, user, password);
        System.out.println(con);

    }

    //方式四

    @Test
    public void testConnect4() throws Exception{
        String url="jdbc:mysql://localhost:3306/test";
        String user="root";
        String password="";

        //省略的部分在mysql中的Driver实现类中有了相应的注册驱动的操作


        //加载Driver
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection(url,user,password);
        System.out.println(con);

    }

    //方式五，最终方式
    //将数据库连接需要的4个基本信息声明在配置文件中，通过读取配置文件的方式，获取连接

    @Test
    public void testConnect5() throws Exception{
        InputStream is = ConnectDemo1.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        prop.load(is);

        String user=prop.getProperty("user");
        String password=prop.getProperty("password");
        String url = prop.getProperty("url");
        String driverClass = prop.getProperty("driverClass");

        Class.forName(driverClass);

        Connection con = DriverManager.getConnection(url, user, password);
        System.out.println(con);


    }
}
